package com.btb.adapter.utils;

import java.math.BigInteger;
import java.util.Optional;
import java.util.function.Function;

import org.web3j.abi.datatypes.Uint;
import org.web3j.abi.datatypes.Utf8String;
import org.web3j.abi.datatypes.generated.Uint256;

public class Fmt {
	public static Integer btoi(Uint256 val) {
		return Optional.ofNullable(val).map(Uint256::getValue).map(BigInteger::intValue).orElse(null);
	}
	
	public static Integer btoi(Uint256 val, Function<? super Uint, ? extends BigInteger> function) {
		return Optional.ofNullable(val).map(function).map(BigInteger::intValue).orElse(null);
	}
	
	private static Function<? super Uint, ? extends BigInteger> extracted() {
		return Uint::getValue;
	}
	
	public static Integer btoi(Uint val) {
		return Optional.ofNullable(val).map(Uint::getValue).map(BigInteger::intValue).orElse(null);
	}

	public static String utf8tos(Utf8String val) {
		return Optional.ofNullable(val).map(Utf8String::getValue).orElse(null);
	}

	public static Long btol(Uint256 val) {
		return Optional.ofNullable(val).map(extracted()).map(BigInteger::longValue).orElse(null);
	}
	public static Long btol(Uint val) {
		return Optional.ofNullable(val).map(extracted()).map(BigInteger::longValue).orElse(null);
	}

	public static BigInteger intToBig(Integer val) {
		return Optional.ofNullable(val).map(String::valueOf).map(BigInteger::new)
				.orElseThrow(() -> new IllegalStateException("intToBig val is null"));
	}

	public static BigInteger logToBig(Long val) {
		return Optional.ofNullable(val).map(String::valueOf).map(BigInteger::new)
				.orElseThrow(() -> new IllegalStateException("logToBig val is null"));
	}
}
